package com.ttc.mBackupK16.BackupPhotos;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.ttc.mBackupK16.R;

public class PhotosListActivity extends Activity implements OnClickListener {
	private int count;
	private Bitmap[] thumbnails;
	private boolean[] thumbnailsselection;
	private String[] arrPath;
	private static final int VIEW_IMAGE = 1;
	private ImageAdapter imageAdapter;
	private long lastId;
	public GridView imageGrid;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photos_list);

		GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
		imageAdapter = new ImageAdapter();
		imageAdapter.initialize();
		imagegrid.setAdapter(imageAdapter);
		Log.i("tag", "herre");

		Button btnBackupPhotos, btnCancelPhotos;
		CheckBox chBCheckAllPhotos;

		btnBackupPhotos = (Button) findViewById(R.id.btnBackupPhotos);
		btnCancelPhotos = (Button) findViewById(R.id.btnCancelPhotos);
		chBCheckAllPhotos = (CheckBox) findViewById(R.id.chBCheckAllPhotos);
		
		btnBackupPhotos.setOnClickListener(this);
		btnCancelPhotos.setOnClickListener(this);
		chBCheckAllPhotos.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnBackupPhotos:
			final int len = imageAdapter.images.size();
			int cnt = 0;
			ArrayList<Integer> selectImages = new ArrayList<Integer>();
			for (int i = 0; i < len; i++) {
				if (imageAdapter.images.get(i).selection) {
					cnt++;
					selectImages.add(imageAdapter.images.get(i).id);
				}
			}
			if (cnt == 0) {
				Toast.makeText(getApplicationContext(),
						"Please select at least one image",
						Toast.LENGTH_LONG).show();
			} else {
				Intent intent = new Intent(getApplicationContext(),
						SelectedListActivity.class);
				intent.putIntegerArrayListExtra("Ids", selectImages);
				startActivity(intent);

			}
			break;
		case R.id.btnCancelPhotos:
			this.finish();
			break;
		case R.id.chBCheckAllPhotos:
			Toast.makeText(getBaseContext(), "CheckAll Photos clicked!", Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.mnu_file_list:
			Intent i = new Intent(getApplicationContext(),
					RestoreActivity.class);
			startActivity(i);
			return true;
		case R.id.help:
			// showHelp();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public class ImageAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		public ArrayList<ImageItem> images = new ArrayList<ImageItem>();

		public ImageAdapter() {
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public void initialize() {
			images.clear();
			final String orderBy = MediaStore.Images.Media._ID;
			final String[] columns = { MediaStore.Images.Thumbnails._ID };
			Cursor imageCursor = managedQuery(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
					null, null, orderBy);
			if (imageCursor != null) {
				int image_column_index = imageCursor
						.getColumnIndex(MediaStore.Images.Media._ID);
				for (int i = 0; i < imageCursor.getCount(); i++) {
					imageCursor.moveToPosition(i);
					int id = imageCursor.getInt(image_column_index);
					ImageItem item = new ImageItem();
					item.id = id;
					lastId = id;
					item.img = MediaStore.Images.Thumbnails.getThumbnail(
							getContentResolver(), id,
							MediaStore.Images.Thumbnails.MICRO_KIND, null);
					images.add(item);
				}
				imageCursor.close();
			}
			notifyDataSetChanged();
		}

		public int getCount() {
			return images.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.galleryitem, null);
				holder.imageview = (ImageView) convertView
						.findViewById(R.id.thumbImage);
				holder.checkbox = (CheckBox) convertView
						.findViewById(R.id.itemCheckBox);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			ImageItem item = images.get(position);
			holder.checkbox.setId(position);
			holder.imageview.setId(position);
			holder.checkbox.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					CheckBox cb = (CheckBox) v;
					int id = cb.getId();
					if (images.get(id).selection) {
						cb.setChecked(false);
						images.get(id).selection = false;
					} else {
						cb.setChecked(true);
						images.get(id).selection = true;
					}
				}
			});
			holder.imageview.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					int id = v.getId();
					ImageItem item = images.get(id);
					Intent intent = new Intent();
					intent.setAction(Intent.ACTION_VIEW);

					final String[] columns = { MediaStore.Images.Media.DATA };
					// get the Cursor of the image base on image id
					Cursor imageCursor = managedQuery(
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							columns, MediaStore.Images.Media._ID + " = "
									+ item.id, null,
							MediaStore.Images.Media._ID);

					if (imageCursor != null && imageCursor.getCount() > 0) {
						imageCursor.moveToPosition(0);
						// get absoluted image path

						String path = imageCursor.getString(imageCursor
								.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));

						File file = new File(path);

						imageCursor.close();
						intent.setDataAndType(Uri.fromFile(file), "image/*");
						startActivityForResult(intent, VIEW_IMAGE);
					}
				}
			});
			holder.imageview.setImageBitmap(item.img);
			holder.checkbox.setChecked(item.selection);
			return convertView;
		}
	}

	class ViewHolder {
		ImageView imageview;
		CheckBox checkbox;
		int id;
	}

	class ImageItem {
		boolean selection;
		int id;
		Bitmap img;
	}
}